package com.uenpay.im.ui.old.activity.chat;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ProgressBar;

import com.qiyunxin.android.http.utils.FileUtils;
import com.qiyunxin.android.http.utils.IDownloadProgress;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.protocol.QyxMsg;
import com.qyx.android.utilities.DateUtils;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.DownloadFileEntity;
import com.uenpay.im.entities.chatbean.MsgVideoModel;
import com.uenpay.smallvideo.MediaRecorderBase;
import com.uenpay.smallvideo.util.DeviceUtils;
import com.uenpay.smallvideo.util.StringUtils;
import com.uenpay.smallvideo.views.SurfaceVideoView;


/**
 * 通用单独播放界面
 *
 * @author tangjun
 */
public class VideoPlayerActivity extends AppCompatActivity implements
        SurfaceVideoView.OnPlayStateListener, OnErrorListener,
        OnPreparedListener, OnClickListener, OnCompletionListener,
        OnInfoListener {

    /**
     * 播放控件
     */
    private SurfaceVideoView mVideoView;
    /**
     * 暂停按钮
     */
    private View mPlayerStatus;
    private View mLoading;

    /**
     * 播放路径
     */
    private String mPath,payPath;
    /**
     * 是否需要回复播放
     */
    private boolean mNeedResume;
    private QyxMsg message = null;
    private ProgressBar download_progressBar;
    private TalkMsgManager takeMsgManager = new TalkMsgManager();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 防止锁屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        IMApplication.getInstance().addActivity(this);

        mPath = getIntent().getStringExtra("path");
        if (StringUtils.isEmpty(mPath)) {
            finish();
            return;
        }

        setContentView(R.layout.activity_video_player);
        mVideoView = (SurfaceVideoView) findViewById(R.id.videoview);

        int screenWidth = getScreenWidth(this);
//        int videoHight = (int) (screenWidth / (MediaRecorderBase.SMALL_VIDEO_WIDTH / (MediaRecorderBase.SMALL_VIDEO_HEIGHT * 1.0f)));
        mVideoView.getLayoutParams().height = getScreenHeight(this);
        mVideoView.requestLayout();

        mPlayerStatus = findViewById(R.id.play_status);
        mLoading = findViewById(R.id.loading);
        download_progressBar = (ProgressBar) findViewById(R.id.download_progressBar);

        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnPlayStateListener(this);
        mVideoView.setOnErrorListener(this);
        mVideoView.setOnClickListener(this);
        mVideoView.setOnInfoListener(this);
        mVideoView.setOnCompletionListener(this);

//		mVideoView.getLayoutParams().height = DeviceUtils.getScreenWidth(this);

        findViewById(R.id.root).setOnClickListener(this);
        Log.e("视频路径：", mPath);
        if (mPath.startsWith(APIConfiguration.getBaseUrl())) {
            // 网络地址
            Bundle mBundle = getIntent().getExtras();
            message = mBundle.getParcelable("mQyxMsg");
            if (message != null) {
                MsgVideoModel msgVideoModel = (MsgVideoModel) message.baseContentModel;
                if(msgVideoModel != null){
                    downloadFile(msgVideoModel.getAttachmentModel().getFileHash());
                }
            } else {
                downloadFile(DateUtils.getCurrentSeconds() + "");
            }

        } else {
            mVideoView.setVideoPath(mPath);
        }

    }

    private void downloadFile(final String fileName) {
        final FileUtils fileUtils = new FileUtils(IMApplication.appName);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String localFilePath = "";

                localFilePath = fileUtils.downloadFile1(mPath,
                        "mp4", fileName, new IDownloadProgress() {
                            @Override
                            public void onProgress(long total, long down_total) {
                                Message msg = myHandler.obtainMessage();
                                DownloadFileEntity download_entity = new DownloadFileEntity();
                                download_entity.total = total;
                                download_entity.download_total = down_total;
                                msg.what = 1;
                                msg.obj = download_entity;
                                myHandler.sendMessage(msg);
                            }
                        });
                if (TextUtils.isEmpty(localFilePath)) {
                    Message msg = myHandler.obtainMessage();
                    msg.what = 2;
                    myHandler.sendMessage(msg);
                    IMApplication.showToast(getResources().getString(
                            R.string.download_file_failure));
                    return;
                } else {
                    if (message != null) {
                        message.baseContentModel.getAttachmentModel().setFileLocalPath(localFilePath);
                    }else{
                        payPath = localFilePath;
                    }
                    Message msg = myHandler.obtainMessage();
                    msg.what = 0;
                    myHandler.sendMessage(msg);
                    if (message != null) {
                        takeMsgManager.updateMsgFilePath(message._id, localFilePath);
                        Intent intent = new Intent(
                                BroadcastAction.UPDATE_DOWNLAOD_FILE_STAUS);
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("msg", message);
                        intent.putExtras(bundle);
                        sendBroadcast(intent);
                    }
                }
            }
        }).start();
    }


    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                if (download_progressBar != null) {
                    download_progressBar.setVisibility(View.GONE);
                    // TODO: 2017/2/17 播放视频
                    if (message != null) {
                        mVideoView.setVideoPath(message.baseContentModel.getAttachmentModel().getFileLocalPath());
                    } else {
                        mVideoView.setVideoPath(payPath);
                    }

                }
            } else if (msg.what == 1) {
                DownloadFileEntity download_entity = (DownloadFileEntity) msg.obj;
                if (download_entity.total > 0) {
                    download_progressBar
                            .setProgress((int) (download_entity.download_total * 100 / download_entity.total));
                }
            }
            return false;
        }
    });

    public int getScreenWidth(Activity context) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        getWindowManager().getDefaultDisplay()
                .getMetrics(dm);
        int W = dm.widthPixels;
//        int temp = getIntent().getIntExtra("width",480);
//        if(temp < W){
//            W = temp;
//        }
        return W;
    }

    public int getScreenHeight(Activity context) {
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        int W = mDisplayMetrics.heightPixels / 3;
//        int temp = getIntent().getIntExtra("height",960);
//        if(temp < W){
//            W = temp;
//        }
        return W;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mVideoView != null && mNeedResume) {
            mNeedResume = false;
            if (mVideoView.isRelease())
                mVideoView.reOpen();
            else
                mVideoView.start();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mVideoView != null) {
            if (mVideoView.isPlaying()) {
                mNeedResume = true;
                mVideoView.pause();
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mVideoView != null) {
            mVideoView.release();
            mVideoView = null;
        }
        IMApplication.getInstance().removeActivity(this);
        super.onDestroy();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mVideoView.setVolume(SurfaceVideoView.getSystemVolumn(this));
        mVideoView.start();
        // new Handler().postDelayed(new Runnable() {
        //
        // @SuppressWarnings("deprecation")
        // @Override
        // public void run() {
        // if (DeviceUtils.hasJellyBean()) {
        // mVideoView.setBackground(null);
        // } else {
        // mVideoView.setBackgroundDrawable(null);
        // }
        // }
        // }, 300);
        mLoading.setVisibility(View.GONE);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getKeyCode()) {// 跟随系统音量走
            case KeyEvent.KEYCODE_VOLUME_DOWN:
            case KeyEvent.KEYCODE_VOLUME_UP:
                mVideoView.dispatchKeyEvent(this, event);
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onStateChanged(boolean isPlaying) {
        mPlayerStatus.setVisibility(isPlaying ? View.GONE : View.VISIBLE);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        if (!isFinishing()) {
            // 播放失败
        }
        finish();
        return false;

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.videoview || i == R.id.root) {
            finish();

        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (!isFinishing())
            mVideoView.reOpen();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                // 音频和视频数据不正确
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                if (!isFinishing())
                    mVideoView.pause();
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                if (!isFinishing())
                    mVideoView.start();
                break;
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                if (DeviceUtils.hasJellyBean()) {
                    mVideoView.setBackground(null);
                } else {
                    mVideoView.setBackgroundDrawable(null);
                }
                break;
        }
        return false;
    }

}
